import 'dart:convert';
import 'dart:io';

import 'package:demo/config/build_config.dart';
import 'package:demo/core/network/bean/base_response.dart';
import 'package:demo/core/network/bean/response_result_code.dart';
import 'package:demo/core/network/exception/response_exception.dart';
import 'package:dio/dio.dart';

import '../http.dart';

/// 请求接口响应后对应的中间件
class ResponseAfterInterceptors extends InterceptorsWrapper {
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    /// 暂不拦截流数据的返回
    if (response.requestOptions.responseType == ResponseType.stream) return handler.resolve(response);

    /// 这里为百度图片的接口适配，因为对应不是我们预设后台数据格式，直接通过
    if (response.requestOptions.path.contains(BuildConfig.shared.getBaiduPictureHostUrl)) {
      return handler.resolve(response);
    }

    if (response.data is String) response.data = json.decode(response.data);

    /// 判断对应的http状态码,自行可新增需要处理的httpStatusCode
    switch (response.statusCode) {
      case HttpStatus.ok:
        {
          /// 解析数据,检查对应的业务逻辑状态码,这里自行定义
          final BaseResponse baseResponse = BaseResponse.fromJson(response.data);
          response.data = baseResponse;

          /// 检查对应的业务逻辑状态码
          switch (baseResponse.code) {

            /// 成功
            case ResponseResultCode.OK:
              return handler.resolve(response);

            /// token失效
            case ResponseResultCode.TOKEN_EXPIRE:
              {
                // 清空等待队列
                HttpClientDio.instance.clear();
                return handler.reject(
                  DioError(
                    requestOptions: response.requestOptions,
                    response: response,
                    error: responseExceptionMap[baseResponse.code],
                  ),
                );
              }

            default:
              return handler.reject(
                DioError(
                  requestOptions: response.requestOptions,
                  response: response,
                  error: responseExceptionMap[baseResponse.code],
                ),
              );
          }
        }

      default:
        return handler.reject(
          DioError(
            requestOptions: response.requestOptions,
            response: response,
            error: responseExceptionMap[ResponseResultCode.OTHER_HTTP_CODE],
          ),
        );
    }
  }
}
